package com.swingson.properties.impl;

import com.swingson.SwingsonGui;
import com.swingson.event.ValueEvent;
import com.swingson.jsonparser.JsonElement;
import com.swingson.other.ConditionAndAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JComponent;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.compiler.ExecutableAccessor;

/**
 * @author Dmitry
 */
public abstract class BaseMvelPropertyProcessor extends PropertyProcessors.PrimitivePropertyProcessor {
    public abstract ValueEvent getEvent(JsonElement jsonElement, JComponent component, SwingsonGui gui);

    @Override
    protected Object getValue(JsonElement jsonElement, JComponent component, SwingsonGui gui, String propertyName) {
        String value = jsonElement.getAsString();
        ParserContext context = new ParserContext();
        MVEL.analyze(value, context);
        Map<String, Class> inputsMap = context.getInputs();
        List<String> inputsList = new ArrayList<>(inputsMap.keySet());
        ExecutableAccessor compiledExpression = (ExecutableAccessor) MVEL.compileExpression(value);
        ValueEvent event = getEvent(jsonElement, component, gui);
        ConditionAndAction conditionAndAction = new ConditionAndAction(compiledExpression, event);
        conditionAndAction.addInputVariables(inputsList);
        gui.addSwingularComponent(component, inputsList, conditionAndAction);
        return component;
    }

    public boolean isTrue(Object value) {
        if (value == null) {
            return false;
        }

        if (value instanceof String) {
            String string = (String) value;
            if (string.isEmpty()) {
                return false;
            }

            return string.equalsIgnoreCase("true");
        }

        if (value instanceof Boolean) {
            return (boolean) value;
        }

        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        }

        return false;
    }
}
